﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PsTFS.Objects;
using PsTFS.Objects.Methodes;

namespace PsTFS.Commandes.Get
{
    /// <summary>
    /// Permet l'éxcution d'une requete
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "WIs")]
    public class Get_Wis: PsCmdlet
    {
        /// <summary>
        /// Constructeur et initialisation des données
        /// </summary>
        public Get_Wis()
        {
            this.StoredQuery = string.Empty;
            this.Query = string.Empty;
        }

        /// <summary>
        /// Lancement du processus
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                List<WorkItem> lp = new List<WorkItem>();
                WorkItemStore witstore = Methode_Service.WIS();
                string projet = string.Empty;

                if (Context.GetContext().Project != null)
                    projet = Context.GetContext().Project.Name;

                WorkItemCollection wic = null;
                if (!string.IsNullOrEmpty(projet))
                {
                    if (!string.IsNullOrEmpty(this.StoredQuery))
                    {
                        StoredQueryCollection sqc = witstore.Projects[projet].StoredQueries;
                        foreach (StoredQuery sq in sqc)
                        {
                            if (sq.Name.ToLower() == this.StoredQuery.ToLower())
                            {
                                wic = witstore.Query(sq.QueryText.Replace("@project", "'" + projet + "'"));
                            }
                        }
                        if (wic == null)
                        {
                            ErrorRecord err = new ErrorRecord(new NullReferenceException("Not stored query"), "<ID>", ErrorCategory.WriteError, null);
                            WriteError(err);
                        }
                    }
                    else
                    {
                        wic = witstore.Query("Select [System.ID] from WorkItem WHERE [System.TeamProject] = '" + projet + "'");
                    }
                }
                else if (!string.IsNullOrEmpty(this.Query))
                {
                    wic = witstore.Query(Query);
                }
                else
                {
                    wic = witstore.Query("Select [System.ID] from WorkItem");
                }

                foreach (WorkItem wi in wic)
                {

                    lp.Add(wi);
                }

                //Retourne l'assembly compilée
                WriteObject(lp);
            }
            catch (PsTFSException ex)
            {
                ErrorRecord err = new ErrorRecord(ex, ex.ObjectError.ToString(), ErrorCategory.WriteError, null);
                WriteError(err);
                Log.AddLog(null, ex.StackTrace);
            }
            finally
            {
                base.ProcessRecord();
            }

        }

        /// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Get-WIs is end");
            base.EndProcessing();
        }
        /// <summary>
        /// Object contenant Team Foundation Server
        /// </summary>
        [Parameter(Position = 0)]
        public TeamFoundationServer TFS
        {
            set { Context.GetContext().Tfs = value; }
        }
        /// <summary>
        /// Nom du label
        /// </summary>
        [Parameter(Position = 1)]
        public string ProjectName
        {
            set { Context.GetContext().Project = Methode.GetProject(value); }
        }

        /// <summary>
        /// Requête pour la récupération de WI
        /// </summary>
        [Parameter(Position = 2)]
        public String Query { get; set; }

        /// <summary>
        /// Nom de la procedure de WI
        /// </summary>
        [Parameter(Position = 3)]
        public String StoredQuery { get; set; }
    }
}